package cn.seaboot.admin.mvc.jackson;

import cn.seaboot.commons.core.LocalDateUtils;
import cn.seaboot.commons.lang.P;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * 对 jackson 进行内容补充
 * <p>
 * 默认参数配置：{@link JacksonProperties}
 *
 * @author Mr.css
 * @version 2022-01-21 10:43
 */
@Configuration
public class JacksonConfiguration {

    @Resource
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init() {
        // 空值不序列化
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        // 设置地区为中国
        objectMapper.setLocale(P.locale());
        // 设置北京时区
        objectMapper.setTimeZone(P.timeZone());

        // 日期序列化
        SimpleModule module = new SimpleModule();
        module.addSerializer(new LocalTimeSerializer(LocalDateUtils.DATE));
        module.addSerializer(new LocalDateSerializer(LocalDateUtils.TIME));
        module.addSerializer(new LocalDateTimeSerializer(LocalDateUtils.DATETIME));

        // 日期反序列化
        module.addDeserializer(LocalDate.class, new LocalDateDeserializer(LocalDateUtils.DATE));
        module.addDeserializer(LocalTime.class, new LocalTimeDeserializer(LocalDateUtils.TIME));
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(LocalDateUtils.DATETIME));

        objectMapper.registerModule(module);
    }
}
